let tbody = document.querySelector("tbody");

function render() {
  axios({
    url: "/score/list",
  }).then(function (res) {
    console.log(res);
    let data = res.data.data;
    let str = "";
    for (let key in data) {
      str += `
        <tr data-id='${key}'>
          <th scope="row">${key}</th>
          <td>${data[key].name}</td>
          <td class="score" data-batch='1' >${data[key].score[0]}</td>
          <td class="score" data-batch='2' >${data[key].score[1]}</td>
          <td class="score" data-batch='3' >${data[key].score[2]}</td>
          <td class="score" data-batch='4' >${data[key].score[3]}</td>
          <td class="score" data-batch='5' >${data[key].score[4]}</td>
        </tr>
            `;
    }
    tbody.innerHTML = str;
  });
}
render();

// 单击单元格
tbody.addEventListener("click", function (e) {
  if (e.target.className == "score") {
    let td = e.target;
    let score = td.innerHTML;
    td.innerHTML = "";
    let myinput = document.createElement("input");
    td.appendChild(myinput);
    myinput.focus();
    myinput.value = score;
    myinput.addEventListener("blur", function () {
      td.innerHTML = score;
    });

    myinput.addEventListener("keydown", function (e) {
      if (e.key == "Enter") {
        axios({
          url: "/score/entry",
          method: "post",
          data: {
            stu_id: td.parentNode.dataset.id,
            batch: td.dataset.batch,
            score: myinput.value,
          },
        }).then(function (res) {
          toastr.success("录入或修改成功");
          td.innerHTML = "";
          td.innerText = myinput.value;
        });
      }
    });
  }
});
